#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import optparse
import os
import os.path
import platform
import re
import subprocess
import sys
import tempfile

#~ Set up global variables for mplayer and avidemux.
mplayerApp = "mplayer"
avidemuxApp = "avidemux2_cli"
if platform.platform().startswith( "Win" ):
    mplayerApp = "c:/users/juruotsa/tools/megui/tools/mencoder/mplayer.exe"
    avidemuxApp = "c:/users/juruotsa/tools/avidemux/avidemux2_cli.exe"

#~ Determine autocropping.
def j264_tool_framerate( videoFile ):
    # Start mplayer in identify mode.
    cmd = mplayerApp + " -identify -frames 20 -vo null -ao null -nocache -speed 100 -noframedrop -vf cropdetect=24:2 %s" % ( videoFile )
    mplayer = subprocess.Popen( cmd, shell = True, bufsize = 128,
          stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, close_fds = False )
    fpsValue = 0
    for _line in mplayer.stdout:
        line = _line.decode().strip()
        if line.startswith( "ID_VIDEO_FPS=" ):
            fpsValue = int( float( line.split( "=" )[1] ) )
    return fpsValue

# Main.
if __name__ == "__main__":
    #~ Handle options.
    usageString = "%prog [options] input-file"
    parser = optparse.OptionParser( usage = usageString )
    parser.add_option( "-k",
                    "--keep-script", dest = "keep_script",
                    action = "store_true",
                    default = False,
                    help = "Flag to control script file auto delete." )
    ( options, args ) = parser.parse_args()
    #~ Sanity checking.
    if not len( args ):
        print( ">>>No input file specified", file = sys.stderr )
        parser.parse_args( ["-h"] )

    # Autocrop.
    fpsValue = j264_tool_framerate( args[0] )

    # Get encoding script.
    scriptSkeleton = None
    scriptSkeleton = open( os.path.split( os.path.abspath( sys.argv[0] ) )[0] + os.sep + "canon_hd.js" )

    # Get an absolute path to target file, since the following chdir()
    # messes up the abspath() -call into some relative directory stuff.
    targetPath = os.path.abspath( args[0] )

    #~ CD to video file's directory.
    videoPath, videoFile = os.path.split( os.path.abspath( args[0] ) )
    os.chdir( videoPath )

    # Save script while doing script replacements.
    scriptFile = tempfile.NamedTemporaryFile( prefix = "j264-", delete = options.keep_script )
    scriptFile.close()
    realScriptFile = open( scriptFile.name, "w" )
    #~ Write mandatory script header.
    realScriptFile.write( "//AD\n" );
    for line in scriptSkeleton:
        line = line.strip()
        #~ L I N E S    T O    P R O C E S S:
        #~ Tweak the file to load.
        if line.startswith( "app.load" ):
            #~ app.load("C:/Users/juruotsa/Documents/Python projects/rock_n_roll/001.m2v.idx");
            line = "app.load(\"%s.idx\");\n" % videoFile
        #~ Tweak frame rate.
        elif line.startswith( "app.video.setFps1000" ):
            line = "app.video.setFps1000=%d;\n" % ( 1000 * fpsValue )
        #~ Tweak container and  set output
        elif line.startswith( "app.setContainer" ):
            line = "\napp.setContainer(\"MP4\");\n"
            line = line + "app.save(\"%s.mp4\");\n" % ( targetPath )
        #~ L I N E S    T O    I G N O R E:
        #~ unnecessary assignments
        #~ audio stuff
        #~ unnecessary function calls
        #~ ignore comments and empty lines
        #~ pre-existing crop and resize filters
        elif line.split( "=" )[0] in ["app.markerA",
            "app.markerB"] or \
            line.split( "(" )[0] in ["app.clearSegments",
            "app.addSegment",
            "app.rebuildIndex"] or \
            line.startswith( "//" ) or \
            line.startswith( "/*" ) or \
            len( line ) == 0:
            continue
        else:
            line = line + "\n"
        #~ Write line into script.
        realScriptFile.write( line )
    realScriptFile.close()

    #~ Create index.
    p = subprocess.Popen( avidemuxApp + " --autoindex --load %s" % videoFile, shell = True )
    sts = os.waitpid( p.pid, 0 )
    print( ">>>Index created.", file = sys.stderr )

    # Ready for run.
    #~ print(avidemuxApp+" --run %s"%scriptFile.name)
    p = subprocess.Popen( avidemuxApp + " --run %s" % scriptFile.name, shell = True )
    sts = os.waitpid( p.pid, 0 )

    #~ Let the user know the script's location.
    if options.keep_script:
        print( ">>>Script file is '%s'." % scriptFile.name, file = sys.stderr )
